#!/usr/bin/python3
# _*_ coding: utf-8 _*_
#
# Copyright (C) 2024 - 2024 heihieyouheihei, Inc. All Rights Reserved 
#
# @Time    : 2024/9/12 12:04
# @Author  : Yuyun
# @File    : 使用lambda将list转为Dict.py
# @IDE     : PyCharm

def list_to_dict(list, key_func):
    d = {}
    for item in list:
        k = key_func(item)
        v = item
        list = d.get(k)
        if list is None:
            d[k] = [v]
        else:
            d[k].append(v)

    return d

if __name__ == '__main__':
    list = [
        {"name": "alice", "age": 100},
        {"name": "middle", "age": 100},
        {"name": "bob", "age": 200}
    ]
    # ret = list_to_dict(list, lambda item: item['age'])

    # get_key = lambda item: item['age']
    # ret = list_to_dict(list, get_key)

    #   这种写法格式不太规范
    # ret = list_to_dict(list, lambda item:
    # item['age']
    #                    )

    def get_key(item):
        return item['age']
    ret = list_to_dict(list, get_key)

    print(ret)
